package com.leyou.user.web;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @ClassName : UserController  //类名
 * @Description :   //描述
 * @Author : qingfeng  //作者
 * @Date: 2020-09-21 14:58  //时间
 */
@RestController
@RequestMapping("info")
public class UserController {

    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data")String data,
                                          @PathVariable("type")Integer type){
        /**
         * @Description //TODO 校验手机号或用户名
         * @Param [data, type] data是手机号，type1是用户名，2是手机号
         * @return org.springframework.http.ResponseEntity<java.lang.Boolean>
         */
        return ResponseEntity.ok(userService.exists(data,type));
    }

    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone){
        /**
         * @Description //TODO 发送短信验证码
         * @Param [phone]
         * @return org.springframework.http.ResponseEntity<java.lang.Void>
         */
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result,@RequestParam("code")String code){
        /**
         * @Description //TODO 注册用户
         * @Param [user, code]
         * @return org.springframework.http.ResponseEntity<java.lang.Void>
         */
        if (result.hasErrors()){
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400,msg);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(@RequestParam("username")String username,
                                                               @RequestParam("password")String password){
        return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username,password));
    }
}
